package com.nbcio.modules.crm.contract.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.core.domain.R;
import com.nbcio.modules.crm.contract.domain.CrmContract;
import com.nbcio.modules.crm.contract.domain.CrmContractItem;
import com.nbcio.modules.crm.contract.service.ICrmContractService;
import com.nbcio.modules.crm.contract.service.ICrmContractItemService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * CRM合同管理控制器
 */
@Tag(name = "CRM合同管理")
@RestController
@RequestMapping("/crm/contract")
@RequiredArgsConstructor
public class CrmContractController {

    private final ICrmContractService contractService;
    private final ICrmContractItemService contractItemService;

    /**
     * 分页查询合同
     */
    @GetMapping("/page")
    public R<IPage<CrmContract>> page(
            @RequestParam int pageNum,
            @RequestParam int pageSize,
            @RequestParam(required = false) String contractNo,
            @RequestParam(required = false) String contractName,
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) String contractType,
            @RequestParam(required = false) Long ownerUserId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        LambdaQueryWrapper<CrmContract> qw = new LambdaQueryWrapper<>();
        if (contractNo != null && !contractNo.isEmpty()) {
            qw.like(CrmContract::getContractNo, contractNo);
        }
        if (contractName != null && !contractName.isEmpty()) {
            qw.like(CrmContract::getContractName, contractName);
        }
        if (customerId != null) {
            qw.eq(CrmContract::getCustomerId, customerId);
        }
        if (contractType != null && !contractType.isEmpty()) {
            qw.eq(CrmContract::getContractType, contractType);
        }
        if (ownerUserId != null) {
            qw.eq(CrmContract::getOwnerUserId, ownerUserId);
        }
        if (status != null && !status.isEmpty()) {
            qw.eq(CrmContract::getStatus, status);
        }
        if (startTime != null && endTime != null && !startTime.isEmpty() && !endTime.isEmpty()) {
            qw.between(CrmContract::getCreateTime, startTime, endTime);
        }
        qw.orderByDesc(CrmContract::getCreateTime);
        IPage<CrmContract> page = contractService.page(Page.of(pageNum, pageSize), qw);
        return R.ok(page);
    }

    /**
     * 根据ID查询合同
     */
    @GetMapping("/{id}")
    public R<CrmContract> get(@PathVariable("id") String id) {
        CrmContract contract = contractService.getById(Long.parseLong(id));
        return R.ok(contract);
    }

    /**
     * 查询合同明细列表
     */
    @GetMapping("/{id}/items")
    public R<List<CrmContractItem>> getItems(@PathVariable("id") String id) {
        LambdaQueryWrapper<CrmContractItem> qw = new LambdaQueryWrapper<>();
        qw.eq(CrmContractItem::getContractId, Long.parseLong(id));
        qw.orderByAsc(CrmContractItem::getLineNo);
        List<CrmContractItem> items = contractItemService.list(qw);
        return R.ok(items);
    }

    /**
     * 新增合同
     */
    @PostMapping
    public R<Boolean> create(@RequestBody CrmContract contract) {
        return R.ok(contractService.save(contract));
    }

    /**
     * 更新合同
     */
    @PutMapping("/{id}")
    public R<Boolean> update(@PathVariable("id") String id, @RequestBody CrmContract contract) {
        contract.setContractId(Long.parseLong(id));
        return R.ok(contractService.updateById(contract));
    }

    /**
     * 删除合同
     */
    @DeleteMapping("/{id}")
    public R<Boolean> remove(@PathVariable("id") String id) {
        return R.ok(contractService.removeById(Long.parseLong(id)));
    }

    /**
     * 批量删除合同
     */
    @PostMapping("/batch-delete")
    public R<Boolean> batchDelete(@RequestBody List<String> ids) {
        List<Long> longIds = ids.stream().map(Long::parseLong).collect(Collectors.toList());
        return R.ok(contractService.removeByIds(longIds));
    }

    /**
     * 保存合同明细
     */
    @PostMapping("/{id}/items")
    public R<Boolean> saveItems(@PathVariable("id") String id, @RequestBody List<CrmContractItem> items) {
        // 先删除原有明细
        LambdaQueryWrapper<CrmContractItem> qw = new LambdaQueryWrapper<>();
        qw.eq(CrmContractItem::getContractId, Long.parseLong(id));
        contractItemService.remove(qw);
        // 保存新明细
        for (CrmContractItem item : items) {
            item.setContractId(Long.parseLong(id));
            item.setItemId(null); // 清除ID，让系统生成新的
        }
        return R.ok(contractItemService.saveBatch(items));
    }
}


